<!--
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-07-16 11:24:24
 * @LastEditTime: 2023-05-17 22:02:37
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 系统监控信息展示页
 * @FilePath: \vue3-element-plus-web\src\views\SysManage\Monitor\index.vue
 * Copyright 版权声明
-->
<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;text-align:right;">
      <el-button
        @click="handleSettings()"
        type="primary"
      >
        <el-icon><Setting /></el-icon>
        监控设置
      </el-button>
    </div>
    <el-row :gutter="20" class="count-row-box">
      <el-col  :span="12" :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
        <el-card class="box-card" :body-style="{ padding: '10px 20px' }" shadow="never">
          <template #header>
            <div class="card-header">
              <strong>
                CPU使用率
              </strong>
            </div>
          </template>
          <div class="card-body">
            <v-chart class="chart" :option="optionCpu" autoresize :loading="loading" theme="vintage" />
          </div>
        </el-card>
      </el-col>
      <el-col  :span="12" :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
        <el-card class="box-card" :body-style="{ padding: '10px 20px' }" shadow="never">
          <template #header>
            <div class="card-header">
              <strong>
                内存使用（GB）
              </strong>
            </div>
          </template>
          <div class="card-body">
            <v-chart class="chart" :option="optionMemory" autoresize :loading="loading" theme="vintage" />
          </div>
        </el-card>
      </el-col>
      <el-col  :span="12" :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
        <el-card class="box-card" :body-style="{ padding: '10px 20px' }" shadow="never">
          <template #header>
            <div class="card-header">
              <strong>
                硬盘使用（GB）
              </strong>
            </div>
          </template>
          <div class="card-body">
            <v-chart class="chart" :option="optionDisk" autoresize :loading="loading" theme="vintage" />
          </div>
        </el-card>
      </el-col>
      <el-col  :span="12" :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
        <el-card class="box-card" :body-style="{ padding: '10px 20px' }" shadow="never">
          <template #header>
            <div class="card-header">
              <strong>
                网络使用
              </strong>
            </div>
          </template>
          <div class="card-body">
            <v-chart class="chart" :option="optionNetwork" autoresize :loading="loading" theme="vintage" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { monitorGetSettings, monitorData } from '@/api/SysManage/monitor'
import * as echarts from 'echarts'
echarts
import VChart from 'vue-echarts'
import { setInterval, clearInterval } from 'timers'
// 图标组件
import { Setting } from '@element-plus/icons-vue'

// 当前模块名称
const MODULE_VALUE = 'SYS_MONITOR'

export default {
  name: 'SysMonitor',
  computed: {
    ...mapGetters([
      'drawerReloadPage'
    ])
  },
  components: {
    VChart,
    Setting
  },
  data() {
    return {
      loading: false,
      data: {},
      // CPU使用率
      optionCpu: {
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        xAxis: {
          type: 'category',
          show: false,
          axisPointer: {
            label: {
              formatter: function(params) {
                return (
                  // params.value + (params.seriesData.length ? '：' + params.seriesData[0].data : '')
                  (params.seriesData.length ? params.seriesData[0].data : '')
                )
              }
            }
          }
        },
        yAxis: {
          type: 'value'
          // max: 100
        },
        series: [
          {
            data: [],
            type: 'line',
            symbol: 'none',
            smooth: true,
            areaStyle: {},
            emphasis: {
              focus: 'series'
            }
          }
        ]
      },
      // 内存使用（GB）
      optionMemory: {
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        xAxis: {
          type: 'category',
          show: false,
          axisPointer: {
            label: {
              formatter: function(params) {
                return (
                  // params.value + (params.seriesData.length ? '：' + params.seriesData[0].data : '')
                  (params.seriesData.length ? params.seriesData[0].data : '')
                )
              }
            }
          }
        },
        yAxis: {
          type: 'value',
          max: 0
        },
        series: [
          {
            data: [],
            type: 'line',
            symbol: 'none',
            areaStyle: {
              color: 'rgba(255, 173, 177, 0.4)'
            },
            lineStyle: {
              color: 'rgba(255, 173, 177, 0.4)'
            }
          }
        ]
      },
      // 硬盘使用（GB）
      optionDisk: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: []
        },
        toolbox: {
          feature: {
            // saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            show: false
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: []
      },
      // 网络使用
      optionNetwork: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: []
        },
        toolbox: {
          feature: {
            // saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            show: false
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: []
      },
      timer: null,
      internal: 10
    }
  },
  watch: {
    // 监听 是否重载页面标识 ， true：重载 false：不重载
    drawerReloadPage: {
      handler: async function(val, oldVal) {
        if (val === true) {
          await this.monitorGetSettings()
          clearInterval(this.timer)
          // this.timer = null
          this.timer = setInterval(() => {
            this.monitorData()
          }, this.internal * 1000)
        }
      },
      deep: true
    }
  },
  async activated() {
    // this.loading = true
    // 获取 监控设置 设置信息
    await this.monitorGetSettings()
    // 获取监控数据
    await this.monitorData()
    this.timer = setInterval(() => {
      this.monitorData()
    }, this.internal * 1000)
    // this.loading = false
  },
  deactivated() {
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    // 获取 监控设置 设置信息
    async monitorGetSettings() {
      const res = await monitorGetSettings()
      this.internal = res.data.internal
    },
    // 监控设置
    handleSettings(row) {
      this.$store.dispatch('ShowDrawer', {
        module: MODULE_VALUE,
        type: 'SETTINGS',
        size: '30%',
        params: {
          pageParams: {
          }
        }
      }).then(res => {

      })
    },
    // 获取监控数据
    async monitorData() {
      const res = await monitorData()
      this.data = res.data || {}

      // CPU使用率
      if ((this.optionCpu.series[0].data).length > 30) {
        this.optionCpu.series[0].data.splice(0, 1)
      }
      this.optionCpu.series[0].data.push(this.data.cpu)

      // 内存使用（GB）
      if ((this.optionMemory.series[0].data).length > 30) {
        this.optionMemory.series[0].data.splice(0, 1)
      }
      this.optionMemory.series[0].data.push(this.data.memory.use)
      this.optionMemory.yAxis.max = this.data.memory.total

      // 硬盘使用（GB）
      if ((this.optionDisk.legend.data).length === 0) {
        for (const item of this.data.disk) {
          (this.optionDisk.legend.data).push(item.name)

          this.optionDisk.series.push({
            name: item.name,
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            symbol: 'none',
            emphasis: {
              focus: 'series'
            },
            data: [item.data]
          })
        }
      } else {
        for (const i in this.data.disk) {
          if ((this.optionDisk.series[i].data).length > 30) {
            this.optionDisk.series[i].data.splice(0, 1)
          }
          this.optionDisk.series[i].data.push(this.data.disk[i].data)
        }
      }

      // 网络使用
      // optionNetwork:
      if ((this.optionNetwork.legend.data).length === 0) {
        // 连接数
        (this.optionNetwork.legend.data).push('conn')
        this.optionNetwork.series.push({
          name: 'conn',
          type: 'line',
          // stack: 'Total',
          // areaStyle: {},
          symbol: 'none',
          emphasis: {
            focus: 'series'
          },
          data: [this.data.network.conn]
        })
        // 网卡上传、下载情况
        for (const i in this.data.network.net) {
          for (const ii in this.data.network.net[i]) {
            if (ii === 'recv' || ii === 'send') {
              const name = `${this.data.network.net[i].name}-${ii}`
              this.optionNetwork.legend.data.push(name)
              this.optionNetwork.series.push({
                name: name,
                type: 'line',
                // stack: 'Total',
                // areaStyle: {},
                symbol: 'none',
                emphasis: {
                  focus: 'series'
                },
                data: [this.data.network.net[i][ii]]
              })
            }
          }
        }
      } else {
        // 连接数
        if ((this.optionNetwork.series[0].data).length > 30) {
          this.optionNetwork.series[0].data.splice(0, 1)
        }
        this.optionNetwork.series[0].data.push(this.data.network.conn)
        // 网卡上传、下载情况
        for (const i in this.data.network.net) {
          for (const ii in this.data.network.net[i]) {
            if (ii === 'recv' || ii === 'send') {
              // const name = `${this.data.network.net[i].name}-${ii}`
              if (ii === 'recv') {
                if (this.optionNetwork.series[i * 2 + 1].data.length > 30) {
                  this.optionNetwork.series[i * 2 + 1].data.splice(0, 1)
                }
                this.optionNetwork.series[i * 2 + 1].data.push(this.data.network.net[i][ii])
              }
              if (ii === 'send') {
                if (this.optionNetwork.series[i * 2 + 2].data.length > 30) {
                  this.optionNetwork.series[i * 2 + 2].data.splice(0, 1)
                }
                this.optionNetwork.series[i * 2 + 2].data.push(this.data.network.net[i][ii])
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container{
  :deep(.el-card__header){
    padding: 10px 20px;
  }
  :deep(.el-col){
    margin-bottom: 20px;
  }
  .chart {
    width: 100%;
    height: 300px;
  }
}
</style>
